package org.lib.rabbitmqhello.try1;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.lib.rabbitmqhello.config.RabbitConfig;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class Try1Listener {

	/**
	 * Listener1
	 * @author ben
	 * @date 2021-08-23 22:31:58 CST
	 * @param content
	 */
	// 默认只建立一个 消费者（针对被监听队列）
	@RabbitListener(queues = {RabbitConfig.QUEUE_1}, ackMode="MANUAL")
	// concurrency属性：设置使用 5个 消费者，，更多设置见 源码
	@RabbitListener(queues = {RabbitConfig.QUEUE_1}, ackMode="MANUAL", concurrency = "5")
//	public void processMessage1(String content) {
	public void processMessage1(String content, Channel channel,
			// @Header 必须！否则，异常！
			@Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
		String tname = Thread.currentThread().getName();
		
		log.info("{}: 接收消息1：content={}", tname, content);
		log.info("{}: 手动确认消息1：tag={}, channelNumber={}, channel", tname, tag, channel.getChannelNumber(), channel);
		
		try {
			System.out.println(tname + ": @RabbitListener 开始休眠...60");
			TimeUnit.SECONDS.sleep(60);
			System.out.println(tname + ": @RabbitListener 休眠END.");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		// 确认消息
		channel.basicAck(tag, false);
		log.info("{}: 结束", tname);
	}
	
	/**
	 * Listener2
	 * @author ben
	 * @date 2021-08-27 21:26:30 CST
	 * @param content
	 */
//	@RabbitListener(queues = {RabbitConfig.QUEUE_1}, ackMode="MANUAL")
//	public void processMessage2(String content) {
	public void processMessage2(String content, Channel channel,
			// @Header 必须！否则，异常！
			@Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
		log.info("接收消息2：content={}", content);
		log.info("手动确认消息2：tag={}, channelNumber={}, channel", tag, channel.getChannelNumber(), channel);
		
		// 确认消息
		channel.basicAck(tag, false);
	}
	
}
